package com.action.mvc.auth.context;

import com.action.mvc.auth.dto.Accordion;
import com.action.mvc.auth.entity.User;

import javax.servlet.http.Cookie;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Wuxiang on 2017/4/24.
 */
public class LoginUserCache {
    private static Map<String,User> cache = new HashMap<>();

    private static Map<String,List<Accordion>> userAccordionMap = new HashMap<>();

    public static void put(User user){
        cache.put(user.getName(), user);
        UserContext.setCurrent(user);
    }

    public static User get(String username){
        return cache.get(username);
    }

    public static void setCookie(User user){
        int expire = 1800;//秒
        String source = user.getName() + "$" +user.getPwd();
        byte[] result = Base64.getEncoder().encode(source.getBytes());

        Cookie cookie = new Cookie("auth",new String(result));
        cookie.setMaxAge(expire);
        ResponseContext.getCurrent().addCookie(cookie);
    }

    public static void remove(String username){
        cache.remove(username);
        Cookie cookie = new Cookie("suth" , null);
        ResponseContext.getCurrent().addCookie(cookie);
        UserContext.setCurrent(null);
    }

    public static void setAccorions(String username ,List<Accordion> accordions){
        userAccordionMap.put(username, accordions);
    }

    public static List<Accordion> getAccorions(String username){
        return userAccordionMap.get(username);
    }
}
